﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Policy;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;
using Microsoft.Practices.Unity;
using Microsoft.Surface.Presentation.Controls;
using ScrumTable.BL.DM.DataManagement;
using ScrumTable.Common.Collections;
using ScrumTable.Common.FileSystem;
using ScrumTable.Config.ElementManagement;
using ScrumTable.DL.Data.Common;
using ScrumTable.UI.View.Converter;
using ScrumTable.UI.View.CustomControl;
using ScrumTable.UI.View.Util;
using ScrumTable.UI.View.WinTouch.Win32Interopt;
using ScrumTable.UI.ViewModel;
using ScrumTable.UI.ViewModel.Controller;
using ScrumTable.UI.ViewModel.Data;
using ScrumTable.UI.ViewModel.Tools;

namespace ScrumTable.UI.View.WinTouch.UserControls.Tool
{
    /// <summary>
	/// Interaction logic for SearchScreen.xaml
	/// </summary>
	public partial class WpfReportSelector
	{
	  


        #region Decleration
        //--------------------------------------------------------------------
        // Decleration
        //--------------------------------------------------------------------
        public Dictionary<string, NamedValue> SelectedValues { get; set; }
	    
        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

	  

       
   
        [Dependency]
        public ViewModelReportSelector Model
        {
            set
            {
                  DataContext = value;
            }
            get
            {
                return (ViewModelReportSelector)DataContext;
            }

        }

        /// <summary>
        /// If true, the controls allows to select a value
        /// </summary>
        public bool IsSelectMode { get; set; }

      
        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        public WpfReportSelector()
        {
            InitializeComponent();
            Loaded += OnLoaded;
        }

       


        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        protected override void ReleaseManagedResources()
        {
            Content = null;
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        void OnLoaded(object sender, RoutedEventArgs e)
        {
            Loaded -= OnLoaded;
        }



        private void OnReportListSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var report = ReportList.SelectedItem as Report;
            PropertyGrid.Children.Clear();
            SelectedValues = new Dictionary<string, NamedValue>();

            if (report == null)
            {
                return;
            }

            WrapPanelAlignAnimated panel = new WrapPanelAlignAnimated();


            foreach (var def in report.FieldMeta)
            {
                // init default value from configuration
                var config = Model.ElementManager.GetReport(report.Name);
                SetDefaultValue(def, config);

                // create controls and assign them to parent panel
                if (def.AllowedValuesTyped.Count() > 0)
                {
                    var control = new ComboBox() {ItemTemplate = Resources["ComboBoxDataTemplate"] as DataTemplate, Style = FindResource("SurfaceComboBoxStyleCustom") as Style};
                    BindingUtil.BindSourcePath(control, ItemsControl.ItemsSourceProperty, "AllowedValues", def, BindingMode.OneWay);
                    BindingUtil.BindSourcePath(control, Selector.SelectedItemProperty, "SelectedValues[" + def.Name + "]", this);
                    var groupBox = new GroupBox {Header = def.DisplayName, Content = control, BorderThickness = new Thickness(0)};
                    panel.Children.Add(groupBox);
                }
                else if(def.FieldTypeName == "DateTime")
                {
                    var control = new DatePicker();
                    BindingUtil.BindSourcePath(control, DatePicker.SelectedDateProperty, "SelectedValues[" + def.Name + "]", this, new ConvertNamedValueToDateTime());
                    var groupBox = new GroupBox { Header = def.DisplayName, Content = control };
                    panel.Children.Add(groupBox);
                }
            }

            ShowImage();
            PropertyGrid.Children.Add(panel);
        }
       
	    private void SetDefaultValue(DomainMeta<NamedValue> def, ReportConfig config)
	    {
            SelectedValues[def.Name] = def.DefaultValueTyped;
	        
	        if( config !=null)
	        {
	            var parameter = config.Parameter.FirstOrDefault(x => x.Left == def.Name);
	            if (parameter != null)
	            {
	                //check if the saved value is stil ok
                    if (!def.AllowedValues.IsEmpty())
                    {
                        SelectedValues[def.Name] = def.AllowedValuesTyped.FirstOrDefault(x => x.Value == parameter.Right);
                    }
                    else if (parameter.Right != null)
                    {
                        SelectedValues[def.Name] = new NamedValue(def.Name, parameter.Right);
                    }
	            }
	        }
	    }

	    private void OnGenerateClick(object sender, RoutedEventArgs e)
        {
            ShowImage();
        }

	    private void ShowImage()
	    {
	        var report = ReportList.SelectedItem as Report;
	        if (report == null) { return; }
             
	        var pairs = (from value in SelectedValues 
                         where  value.Value != null
                         select new Pair<string, string>(value.Key, value.Value.Value)).ToList();
	        var post = report.ToPostCommandArguments(pairs);
	        AsyncImage.WebPostWebPair = new Pair<Uri, string>(report.FullPath, post);
            Model.ElementManager.SetReport(report.Name, pairs);

            if (IsSelectMode && Model.SelectReportCommand.CanExecute(ReportList.SelectedItem))
            {
                Model.SelectReportCommand.Execute(ReportList.SelectedItem);
            }
	    }

	    #endregion
    }
}